'''
@author: Aurelien Deharbe


This file is part of Cute-Server.

Cute-Server is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Cute-Server is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Cute-Server.  If not, see <http://www.gnu.org/licenses/>.
'''

from PySide.QtCore import QCoreApplication, QThread, QMutex
from PySide.QtCore import Slot, Signal
from cclientthread import CClientThread
import socket
import re

class CBridgeThread(QThread):
    
    command = Signal(str, CClientThread)
    script = Signal(str, str, CClientThread)
    killme = Signal(CClientThread)
    
    def __init__(self, sessid, servhost, servport):
        QThread.__init__(self)
        
        self._clients = []
        self._sessid = sessid
        self._servhost = servhost
        self._servport = servport
        
    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self._servhost, self._servport))
        pattern = re.compile(r'QSClient\((.+),([0-9]+)\)')
        mutex = QMutex()
        while True:
            cmd = sock.recv(256).strip()
            if cmd == "QSQuit()":
                break
            r = pattern.match(cmd)
            if r:
                host = r.group(1)
	        port = int(r.group(2))
	        th = CClientThread(host, port, mutex)
	        th.command.connect(self.onCommand)
	        th.script.connect(self.onScript)
	        th.killme.connect(self.onKillMe)
	        th.start()
	        self._clients.append(th)
        sock.close()
        QCoreApplication.exit(0)
    
    @Slot(str, CClientThread)
    def onCommand(self, cmd, client):
        self.command.emit(cmd, client)
    
    @Slot(str, CClientThread)
    def onScript(self, script, name, client):
	self.script.emit(script, name, client)
    
    @Slot(CClientThread)
    def onKillMe(self, client):
        self.killme.emit(client)
        self._clients.remove(client)
        client.wait()


if __name__ == '__main__':
    print "Please use the cuteserver script to run it"
